package com.nbsaas.boot.customer.ext.resource;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.nbsaas.boot.customer.api.apis.CustomerApi;
import com.nbsaas.boot.customer.api.domain.request.CustomerRequest;
import com.nbsaas.boot.customer.api.domain.response.CustomerResponse;
import com.nbsaas.boot.customer.ext.apis.CustomerExtApi;
import com.nbsaas.boot.customer.ext.domain.request.ShopLoginOauthRequest;
import com.nbsaas.boot.customer.ext.domain.response.CustomerExtResponse;
import com.nbsaas.boot.rest.filter.Filter;
import com.nbsaas.boot.rest.response.ResponseObject;
import com.nbsaas.boot.shop.api.apis.ShopOauthTokenApi;
import com.nbsaas.boot.shop.api.domain.field.ShopOauthTokenField;
import com.nbsaas.boot.shop.api.domain.request.ShopOauthTokenRequest;
import com.nbsaas.boot.shop.api.domain.response.ShopOauthTokenResponse;
import com.nbsaas.boot.shop.ext.apis.ShopConfigExtApi;
import com.nbsaas.boot.shop.ext.domain.config.WeChatOauth;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service
public class CustomerExtResource implements CustomerExtApi {

    @Resource
    private ShopConfigExtApi shopConfigExtApi;

    @Resource
    private ShopOauthTokenApi shopOauthTokenApi;

    @Resource
    private CustomerApi customerApi;


    @Transactional
    @Override
    public ResponseObject<CustomerExtResponse> loginShopOauth(ShopLoginOauthRequest request) {
        ResponseObject<CustomerExtResponse> result = new ResponseObject<>();
        ResponseObject<WeChatOauth> res = shopConfigExtApi.info(request.getShop(), WeChatOauth.class);
        if (res.getCode() != 200) {
            result.setCode(res.getCode());
            result.setMsg(res.getMsg());
            return result;
        }
        WxMaService mpService = new WxMaServiceImpl();
        WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
        config.setAppid(res.getData().getAppKey());
        config.setSecret(res.getData().getAppSecret());
        mpService.addConfig("default", config);
        try {
            WxMaJscode2SessionResult session = mpService.getUserService().getSessionInfo(request.getCode());
            ShopOauthTokenResponse token = shopOauthTokenApi.oneData(Filter.eq("shop.id", request.getShop()),
                    Filter.eq(ShopOauthTokenField.openId, session.getOpenid()));

            if (token == null) {
                CustomerRequest customerRequest = new CustomerRequest();
                customerRequest.setName("");
                customerRequest.setPhone("");
                customerRequest.setShop(request.getShop());
                CustomerResponse customer = customerApi.createData(customerRequest);

                ShopOauthTokenRequest tokenDataRequest = new ShopOauthTokenRequest();
                tokenDataRequest.setShop(request.getShop());
                tokenDataRequest.setCustomerId(customer.getId());
                tokenDataRequest.setOpenId(session.getOpenid());
                tokenDataRequest.setUnionId(session.getUnionid());
                tokenDataRequest.setAccessToken(session.getSessionKey());
                shopOauthTokenApi.createData(tokenDataRequest);

                CustomerExtResponse data = new CustomerExtResponse();
                BeanUtils.copyProperties(customer, data);
                data.setOpenId(session.getOpenid());
                result.setData(data);
                return result;
            }
            if (token.getShop() == null) {
                result.setCode(501);
                result.setMsg("获取用户失败");
                return result;
            }

            CustomerResponse customer = customerApi.oneData(Filter.eq("id", token.getCustomerId()));
            CustomerExtResponse data = new CustomerExtResponse();
            BeanUtils.copyProperties(customer, data);
            data.setOpenId(session.getOpenid());
            result.setData(data);

        } catch (WxErrorException e) {
            result.setCode(503);
            result.setMsg("获取用户失败");
            return result;
        }

        return result;
    }
}
